<template>
	<div class="shopcart-container">
		<!-- 全选 清空 -->
		<div class="cart_header">
			<div class="cart_title">
				<!-- 全选 -->
				<van-checkbox checked-color="#000000" icon-size="18" v-model="isCheckedAll" @click="onSelectAll">
					全选
				</van-checkbox>
			</div>
			<div class="cart_clear" @click="onClickDeleteAll">
				<van-icon name="delete" />
				<span>清空</span>
			</div>
		</div>
		<!-- 商品列表区域 -->
		<div style="background-color: white;">
			<van-row v-for="(item, i) in cartList" :key="i" type="flex" align="center">
				<van-col span="2">
					<!-- 复选框 -->
					<van-checkbox v-model="item.is_checked" @change="onCheckedChange(item)" />
				</van-col>
				<van-col span="5">
					<!-- 中间商品图片 -->
					<van-image :src="APIDomainName + item.pic" width="80" height="80" @error="handleImageError(item)"
						:alt="item.title" />
				</van-col>
				<van-col span="17">
					<van-row class="van-multi-ellipsis--l2 title">{{ item.title }}</van-row>
					<van-row type="flex" align="center">
						<van-col span="8" class="price">¥{{ item.price }}</van-col>
						<van-col span="16" class="opration">
							<van-stepper v-model="item.count" @change="onCountChanged(item)" integer />
							<van-button text="删除" size="small" @click.prevent="onClickDeleteCartItem(item.id)" />
						</van-col>
					</van-row>
				</van-col>
			</van-row>
		</div>
		<!-- 商品结算区域 -->
		<van-cell title="商品结算" value="总计不含运费"></van-cell>
		<van-cell>
			<template #title>
				已勾选商品<span class="red">{{ getCheckedCount }}</span>
				件，总价
				<span class="red">¥{{ getCheckedAmount }}</span>
			</template>
		</van-cell>
		<!-- 结算按钮 -->
		<van-button type="primary" size="large" @click="onClickCreateOrder">去结算</van-button>
		<!-- 加载状态 -->
		<van-loading v-show="isLoading" />
	</div>
</template>

<script>
	import {
		showConfirmDialog,
		showToast
	} from 'vant';
	import {
		getCartListAPI,
		updateCartCountAPI,
		updateCartCheckedAPI,
		deleteCartAllAPI, // 删除清空购物车接口
		updateCartCheckedAllAPI, // 全选/全不选购物车项接口
	} from '@/api/cart.js';

	export default {
		data() {
			return {
				cartList: [],
				isCheckedAll: false,
				isLoading: false,
				defaultImage: 'https://via.placeholder.com/80x80', // 默认图片
				maxImageRetries: 3, // 图片加载最大重试次数
				retryBaseDelay: 1000, // 重试基础延迟时间（毫秒）
				retryExponent: 2 // 重试指数
			};
		},
		computed: {
			// 计算勾选记录总数
			getCheckedCount() {
				return this.cartList.reduce((sum, item) => item.is_checked ? sum + 1 : sum, 0);
			},
			// 计算是否全部勾选
			getCheckedAll() {
				return this.cartList.length === this.getCheckedCount;
			},
			// 计算总数
			getCheckedAmount() {
				return this.cartList.reduce(
					(amount, item) => item.is_checked ? amount + item.price * item.count : amount,
					0
				);
			},
		},
		methods: {
			// 错误处理方法
			handleError(error, message) {
				console.error(message, error);
				showToast(message + '，请稍后重试');
			},
			// 获取图片 URL
			getImageUrl(item) {
				return this.APIDomainName + item.pic;
			},
			// 处理图片加载错误
			async handleImageError(item, event) {
				const fullUrl = this.getImageUrl(item);
				const errorMessage = event && event.target && event.target.naturalWidth === 0 ?
					'图片加载失败，可能是 404 错误' :
					'图片加载失败，可能是网络问题';
				console.error(`${errorMessage}，商品：${item.title}，路径：${fullUrl}`);

				if (!item.retryCount) {
					item.retryCount = 0;
				}
				if (item.retryCount < this.maxImageRetries) {
					item.retryCount++;
					const retryDelay = this.retryBaseDelay * Math.pow(this.retryExponent, item.retryCount - 1);
					showToast(`商品 ${item.title} 的图片加载失败，正在重试（第 ${item.retryCount} 次）`);
					await new Promise(resolve => setTimeout(resolve, retryDelay));
					item.pic = item.pic; // 触发重新加载
				} else {
					showToast(`商品 ${item.title} 的图片加载失败，将显示默认图片`);
					item.pic = this.defaultImage; // 显示默认图片
				}
			},
			// 获取用户购物车数据
			async getCartData() {
				try {
					this.isLoading = true;
					const result = await getCartListAPI();
					this.cartList = result.data;
					console.log(this.cartList)
					this.isCheckedAll = this.getCheckedAll; // 重置isCheckedAll属性值
				} catch (error) {
					this.handleError(error, '获取购物车列表失败');
				} finally {
					this.isLoading = false;
				}
			},
			// 触发更改购物商品数量
			async onCountChanged(item) {
				const id = item.id;
				const count = item.count;
				const params = {
					id,
					count
				};
				try {
					this.isLoading = true;
					await updateCartCountAPI(params);
					// 直接更新本地数据
					item.count = count;
				} catch (error) {
					this.handleError(error, '更新商品数量失败');
				} finally {
					this.isLoading = false;
				}
			},
			// 触发更改购物商品选中状态
			async onCheckedChange(item) {
				const id = item.id;
				const is_checked = item.is_checked ? 1 : 0;
				const params = {
					id,
					is_checked
				};
				try {
					this.isLoading = true;
					await updateCartCheckedAPI(params);
					this.isCheckedAll = this.getCheckedAll; // 重置isCheckedAll属性值
					// 直接更新本地数据
					item.is_checked = item.is_checked;
				} catch (error) {
					this.handleError(error, '更新商品选中状态失败');
				} finally {
					this.isLoading = false;
				}
			},
			// 触发删除购物商品
			async onClickDeleteCartItem(id) {
				try {
					const shouldDelete = await showConfirmDialog({
						message: '客官，您确定删除该商品吗?'
					});
					if (shouldDelete) {
						this.isLoading = true;
						// 假设此处调用删除单个商品的 API
						// 实际代码中需要补充该 API 调用逻辑
						await new Promise((resolve) => setTimeout(resolve, 1000)); // 模拟延迟
						// 直接更新本地数据
						this.cartList = this.cartList.filter(item => item.id !== id);
					}
				} catch (error) {
					this.handleError(error, '删除商品失败');
				} finally {
					this.isLoading = false;
				}
			},
			// 触发全选/全不选
			async onSelectAll() {
				const is_checked = this.isCheckedAll ? 1 : 0;
				try {
					this.isLoading = true;
					await updateCartCheckedAllAPI(is_checked);
					// 直接更新本地数据
					this.cartList.forEach(item => item.is_checked = is_checked === 1);
					this.isCheckedAll = this.getCheckedAll;
				} catch (error) {
					this.handleError(error, '全选/全不选操作失败');
				} finally {
					this.isLoading = false;
				}
			},
			// 触发清空
			async onClickDeleteAll() {
				const shouldDeleteAll = await showConfirmDialog({
					message: '客官，您确定清空购物车吗?'
				});
				if (shouldDeleteAll) {
					try {
						this.isLoading = true;
						await deleteCartAllAPI();
						// 直接更新本地数据
						this.cartList = [];
						this.isCheckedAll = false;
					} catch (error) {
						this.handleError(error, '清空购物车失败');
					} finally {
						this.isLoading = false;
					}
				}
			},
			// 触发创建订单
			onClickCreateOrder() {
				if (this.cartList.length === 0) {
					showToast("您的购物车为空");
					return;
				}
				// 要确保购物车数据和后端数据库的是一致的 .....
				this.$router.push({
					name: "orderCreate"
				});
			},
		},
		mounted() {
			this.getCartData();
		}
	};
</script>

<style lang="less" scoped>
	.shopcart-container {
		padding: 0px 10px;

		.cart_header {
			padding: 10px;
			margin: 10px 0;
			height: 20px;
			background-color: white;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}

	.van-checkbox {
		justify-content: center;
	}

	.title {
		padding: 5px 5px;
		font-size: 12px;
		line-height: 20px;
	}

	.price {
		padding-left: 10px;
		text-align: left;
		font-size: 16px;
		font-weight: bold;
		color: red;
		display: flex;
		align-items: center;
	}

	.opration {
		padding-right: 10px;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.red {
		color: red;
		font-weight: bold;
		font-size: 16px;
	}
</style>